<template>
  <div class="bar-gadget-css"
       style="width: 100%; height: 100%"
       :id="id">
    <Portal to="right-disable"
            style="width: 100%; height: 100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="hover"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width: 100%; height: 100%; border: 0">
        <el-card shadow="never"
                 style="width: 100%; height: 100%; border: 0; overflow: visible"
                 class="aui-card--fill">
          <div style="width: 100%; height: 100%">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="
              (widgetName && widgetName.trim().length > 0) ||
              (gadgetSetting &&
                gadgetSetting.headerDescription &&
                gadgetSetting.headerDescription.trim().length > 0)
            ">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer="slicer"
                          :gadgetId="id"
                          :gadgetType="gadgetInfo.com"
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section control-section2">
              <div class="content-wrapper"
                   style="width: 100%; height: 100%">
                <div v-if="isHasData"
                     style="width: 100%; height: 100%">
                  <div :id="selfGadgetUuid"
                       style="width: 100%; height: 60%"></div>
                  <div style="width: 100%; height: 40%">
                    <ejs-grid :dataSource="comDataSource.data"
                              height="100%"
                              :allowPaging="Object.prototype.hasOwnProperty.call(gadgetSetting, 'grid') && Object.prototype.hasOwnProperty.call(gadgetSetting.grid, 'showPaging') ? gadgetSetting.grid.showPaging : true"
                              :pageSettings="gadgetSetting.grid.pageSettings || { pageSize: 100, pageSizes: [10, 50, 100, 200, 1000]}"
                              :rowDataBound="rowDataBound"
                              :allowFiltering='true'
                              :allowSorting='true'
                              :showColumnMenu='true'
                              :filterSettings='{ type: "CheckBox" }'
                              :queryCellInfo="customiseCell">
                      <e-columns>
                        <e-column v-for="(columnItem, index) of comDataSource.columns"
                                  :key="index"
                                  width="150"
                                  :template="index === 0?'':formatForGrid['formatNumber']"
                                  :maxWidth="columnItem.maxWidth?columnItem.maxWidth:'auto'"
                                  :kpiField="gadgetSetting.kpiValueField"
                                  :headerTemplate='employeetemplate'
                                  :headerTextTooltip=columnItem.headerTextTooltip
                                  :textAlign="columnItem.textAlign"
                                  :allowFiltering="columnItem.allowFiltering"
                                  :disableHtmlEncode="columnItem.disableHtmlEncode"
                                  :fieldsFormat='fieldsFormat'
                                  :fieldsNewFormat='fieldsNewFormat'
                                  :field="columnItem.field"
                                  :headerText="columnItem.headerText"></e-column>
                      </e-columns>
                    </ejs-grid>
                  </div>
                </div>
                <div v-else
                      class="gadget-no-newdata">
                  <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <div class="widgets-tip"> <a :href="widgetNoDataWiki"
                         :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer="slicer" />
    <DrillThrough :gadgetId="id"
                  :pageId="pageId"
                  :slicer="slicer"
                  :queryId="queryId"
                  :gadgetType="gadgetInfo.com"
                  ref="drill-through"
                  :widgetName="widgetName"
                  :code="code" />
    <div style="position: absolute; left: 9999px">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType="notgridgadget" />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import * as Echarts from 'echarts'
import { getUUID } from '@/utils'
import { groupBy, cloneDeep } from 'lodash'
import bus from '@/components/storybook/utilties/bus'
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime,
    model: () => import('@/components/gadget/query-model/query-model')
  },
  data () {
    return {
      employeetemplate: function () {
        return {
          template: Vue.component('employeetemplate', {
            template: ` <el-tooltip class="item" effect="dark" :content="$data.data.headerTextTooltip" placement="top-start" v-if="$data.data.headerTextTooltip">
                          <div>{{$data.data.headerText}}</div>
                        </el-tooltip>
                         <div v-else>{{$data.data.headerText}}</div>
                        `
          })
        }
      },
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      chartOption: {
        color: [],
        animation: 'auto',
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br />{b}: {c}'
        },
        legend: {
          type: 'scroll',
          top: 20,
          width: '90%',
          data: []
        },
        grid: {
          top: '11%',
          left: '10px',
          right: '10px',
          bottom: '10px',
          width: '95%',
          height: '85%',
          containLabel: true
        },
        xAxis: {
          boundaryGap: true,
          data: [],
          type: 'category',
          axisLabel: {
            rotate: 315,
            formatter: '{value}',
            hideOverlap: true,
            overflow: 'truncate',
            ellipsis: '...'
          },
          name: '',
          nameLocation: 'end',
          nameGap: 5,
          nameRotate: 270
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            inside: false,
            show: true,
            hideOverlap: true,
            overflow: 'truncate',
            ellipsis: '...'
          },
          name: '',
          axisLine: {
            show: true
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true
          }
        },
        series: []
      },
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      theme: 'Material',
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'chartgridgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, {
            gadgetType: 'chartgridgadget'
          }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      conditionFormat: [],
      linkedDatasetList: [],
      fieldsFormat: null,
      fieldsNewFormat: null
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.gadgetHeight = this.gadgetInfo.h * 20 - 45
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
    bus.$on('KpiSettingsRefresh', () => {
      this.query()
    })
  },
  computed: {
    comTimeFrame () {
      return Array.isArray(this.queryData) && this.queryData[0] ? this.queryData[0][this.gadgetSetting.timeFrameField] : null
    },
    comDimension () {
      return Array.isArray(this.queryData) && this.queryData[0] ? this.queryData[0][this.gadgetSetting.userType] : null
    },
    comDataSource () {
      let groupData = groupBy(this.queryData, this.gadgetSetting.dateField)
      let arr = this.queryData.map(v => v[this.gadgetSetting.groupValueField])
      let columns = [...new Set([...arr])]
      let data = []
      Object.keys(groupData)
        .sort()
        .forEach((v) => {
          data.push({
            Date: v
          })
          groupData[v].forEach(vi => {
            if (vi[this.gadgetSetting.groupValueField]) {
              data[data.length - 1][vi[this.gadgetSetting.groupValueField]] =
                vi[this.gadgetSetting.kpiValueField]
            }
          })
        })
      const beforeColumn = this.gadgetSetting.grid.date || [{ headerText: 'Date', field: 'Date' }]
      const handleCol = columns.map(item => {
        return { headerText: item, field: item }
      })
      return {
        columns: beforeColumn.concat(handleCol),
        data
      }
    }
  },
  methods: {
    updateChart (originData) {
      var _self = this
      _self.chartDom = document.getElementById(`${_self.selfGadgetUuid}`)
      if (!_self.chartDom) {
        setTimeout(() => {
          _self.repeatNumber++
          _self.updateChart(originData)
        }, 1000)
      } else if (
        !Array.isArray(originData) ||
        (Array.isArray(originData) && originData.length === 0)
      ) {
        Echarts.init(_self.chartDom).dispose()
      } else {
        // if(_self.chartDom){
        //   Echarts.init(_self.chartDom).dispose()
        // }
        _self.chartOption = _self.$options.data.call(_self).chartOption
        _self.repeatNumber = 0
        let myChart = Echarts.init(_self.chartDom, this.globalTheme)
        this.setChartOption(_self._.toLower(this.gadgetSetting.chartsType))
        myChart.on('click', params => {
          _self.setDrillThroughInfo(params, 'chartgridgadget')
        })
        myChart.setOption(_self.chartOption)
        myChart.on('magictypechanged', function (params) {
          _self.setChartOption(params.currentType)
          myChart.setOption(_self.chartOption)
        });
        _self.$erd.listenTo(_self.chartDom, element => {
          _self.$nextTick(() => {
            _self.resized()
          })
        })
      }
    },
    setChartOption (type) {
      this.typeOption = this.gadgetSetting.chart
      const _self = this
      _self.chartOption = {
        legend: _self.setLegend(),
        xAxis: _self.setXAxis(type),
        yAxis: _self.setYAxis(),
        dataZoom: _self.setDataZoom(),
        series: _self.setSeries(type),
        grid: {
          // top: '11%',
          left: '20px',
          right: '10px',
          bottom: '50px',
          width: '98%',
          // height: '85%',
          containLabel: true
        },
        toolbox: {
          show: true,
          right: '20px',
          feature: {
            magicType: {
              type: ['bar', 'line'],
              title: {
                line: 'Switch to Line Chart',
                bar: 'Switch to Bar Chart'
              }
            }
          }
        },
        tooltip: {
          formatter: params => {
            return `${params.seriesName}: ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.kpiValueField)} <br /> ${params.name}`
          }
        },
      }
    },
    setLegend () {
      let benchMark =
        this.gadgetSetting.benchMark &&
        Array.isArray(JSON.parse(this.gadgetSetting.benchMark)) &&
        JSON.parse(this.gadgetSetting.benchMark).find(
          v =>
            v.timeFrame === this.comTimeFrame &&
            v.dimension === this.comDimension
        )
      let { columns } = cloneDeep(this.comDataSource)
      columns.splice(0, 1)
      let result = columns.map(v => {
        let color = this.setLegendColor(v.field)
        return color
          ? {
            name: v.field,
            itemStyle: { color }
          }
          : v.field
      })
      return {
        data: benchMark ? [...result, benchMark.benchmarkName] : [...result],
        type: 'scroll',
        top: 10,
        width: '60%',
      }
    },
    setXAxis (type) {
      let { columns, data } = cloneDeep(this.comDataSource)
      return [
        {
          type: 'category',
          data: data.map(v => v[columns[0].field]),
          boundaryGap: true
        }
      ]
    },
    setYAxis () {
      // let data = this.queryData
      //   .filter(
      //     v =>
      //       v[this.gadgetSetting.groupValueField] 
      //   )
      //   .map(v => v[this.gadgetSetting.kpiValueField])
      //let min = Math.min(...data)
     // min = min > 0 ? 0 : min
      //let max = Math.max(...data)
      //let minInterval = max - min>5?Math.ceil(parseInt((max - min) / 5) / 10) * 10:1
      return [
        {
          type: 'value',
          interval: Number(this.typeOption.interval) || null,
          name: this.typeOption.measure || this.gadgetSetting.kpiValueField,
          min: this.typeOption.min || null,
          max: this.typeOption.max || null,
          show: this.typeOption.yAxisShow || false,
          nameLocation: this.typeOption.yAxisNameLocation,
          nameGap: this.typeOption.yAxisNameGap,
          axisLabel: {
            formatter: value => {
              return `${this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.kpiValueField)}`
            }
          },
          nameTextStyle: {
            align:'left'
          }
        },
      ]
    },
    setDataZoom () {
      return [
        {
          show: true,
          start: 0,
          end: 100
        },
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ]
    },
    setSeries (type) {
      if(type==='line') {
        let seriesArr = [...this.setDataSeries(type), ...this.setBenchMarkSeries()]
        if(seriesArr[0]){
          seriesArr[0].connectNulls = true
        }
        return seriesArr
      } else {
        return [...this.setDataSeries(type), ...this.setBenchMarkSeries()]
      }
      
    },
    setDataSeries (type) {
      let { columns, data } = cloneDeep(this.comDataSource)
      columns.splice(0, 1)
      return columns.map(v => {
        let color = type === 'line' && this.setLineSeriesColor(v.field)
        return {
          name: v.field,
          smooth: type === 'line' ? this.typeOption.setSmooth : false,
          type,
          itemStyle: color
            ? {
              color
            }
            : {},
          data: data.map((vp, vi) => {
            let color = type === 'bar' && this.setBarSeriesColor(v.field, vp[v.field], vi)
            return color
              ? {
                value: vp[v.field],
                itemStyle: {
                  color
                }
              }
              : vp[v.field]
          })
        }
      })
    },
    setBarSeriesColor (column) {
      try {
        let arr = this.conditionFormat
        let color = ''
        {
          let res = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '=='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '=='
              )
              return v
            })
          let res1 = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '!='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '!='
              )
              return v
            })
          res.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
          res1.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              !it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
        }
        return color
      } catch (error) { }
    },
    setLineSeriesColor (column) {
      try {
        let arr = this.conditionFormat
        let color = ''
        {
          let res = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '=='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '=='
              )
              return v
            })
          let res1 = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '!='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '!='
              )
              return v
            })
          res.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
          res1.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              !it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
        }
        return color
      } catch (error) { }
    },
    setLegendColor (column) {
      try {
        let arr = this.conditionFormat
        let color = ''
        {
          let res = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '=='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '=='
              )
              return v
            })
          let res1 = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField &&
                item.textColor
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '!='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '!='
              )
              return v
            })
          res.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
          res1.reverse().forEach(it => {
            if (
              it &&
              it.textColor &&
              !it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              color = it.textColor
            }
          })
        }
        return color
      } catch (error) { }
    },
    setBenchMarkSeries () {
      let benchMark =
        this.gadgetSetting.benchMark &&
        Array.isArray(JSON.parse(this.gadgetSetting.benchMark)) &&
        JSON.parse(this.gadgetSetting.benchMark).find(
          v =>
            v.timeFrame.toLowerCase() === this.comTimeFrame.toLowerCase() &&
            v.dimension.toLowerCase() === this.comDimension.toLowerCase()
        )
      let { data } = cloneDeep(this.comDataSource)
      return benchMark
        ? [
          {
            name: benchMark.benchmarkName,
            symbol: 'none',
            type: 'line',
            yAxisIndex: 0,
            data: data.map(v => benchMark.benchmark)
          }
        ]
        : []
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = newWPx - 10 + 'px'
    },
    upgradeGadgetSetting (setting) { },
    query (e) {
      this.gadgetSetting = this._.merge(
        this.gadgetSetting,
        this.queryModelDefaultSetting.dataInfo.gadgetSetting
      )
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (
        tempObj['name'] &&
        this.slicer['name'] &&
        tempObj['name'] === this.slicer['name']
      )
        delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType,
        peerGroupId: this.peerGroupId
      }
      _self.queryData = []
      this.$interface.reports
        .getReportDataInfo(param)
        .then(({ data: res }) => {
          try {
            _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields =
              res.selectFields
          } catch (error) { }
          _self.verifyHasData(res)
          if (res.config) {
            _self._.merge(_self.gadgetSetting, res.config)
            if (
              !_self.gadgetSetting.headerDescription ||
              _self.gadgetSetting.headerDescription === null
            ) {
              _self.gadgetSetting.headerDescription = ''
            }
            _self.upgradeGadgetSetting(_self.gadgetSetting)
          }     

          if (res.name) {
            _self.widgetName = res.name
          }else if(this.wName){
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          this.fxFields = res.fxFields || []
          if (res.data) {
            _self.queryData = []
            let temp = this.gadgetSetting.groupValueField
            if (temp) {
              res.data = res.data.map(v => {
                return {
                  ...v,
                  [temp]: typeof v[temp] === 'string' ? v[temp].replaceAll('.', '_') : v[temp]
                }
              })
            }
            this.currentTime = new Date()
            _self.queryData = res.data
            _self.queryFields = res.selectFields
            try {
              _self.fieldsFormat = _self.queryFields.find(i => i.alias === _self.gadgetSetting.kpiValueField).fieldsFormat
              _self.fieldsNewFormat = _self.queryFields.find(i => i.alias === _self.gadgetSetting.kpiValueField).fieldsNewFormat

            } catch (error) {

            }
            _self.conditionFormat = res.conditionFormat.reverse()
            _self.linkedDatasetList = res.datasetSync
            if (_self.queryData) {
              _self.updateChart(_self.queryData)
            }
          }
        })
        .catch(error => {
           if (this.wName) {
            this.widgetName = this.wName
          }
          if (_self.chartDom) {
            Echarts.init(_self.chartDom).dispose()
          }
          _self.isHasData = false
          _self.loading = false
          if (error.response && error.response.status === 504) {
            this.errorStatus = '504'
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        })
        .finally(() => {
          this.currentTime = new Date()
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    },
    load (args) {
      args.chart.series[0].marker.dataLabel.font.color = '#000000'
    },
    rowDataBound (args) {
      args.row.childNodes.forEach(item => {
        if (item.dataset.bgc) {
          args.row.style.backgroundColor = item.dataset.bgc
        }
        if (item.dataset.color) {
          args.row.childNodes.forEach(ii => {
            if (!ii.style.color) {
              ii.style.color = item.dataset.color
            }
          })
        }
      })
    },
    customiseCell (args) {
      try {
        let arr = this.conditionFormat
        var column = args.column.field
        if (args.data) {
          let res = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '=='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '=='
              )
              return v
            })
          let res1 = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting.groupValueField
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting.groupValueField && v.opt === '!='
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting.groupValueField && vi.opt === '!='
              )
              return v
            })
          res.reverse().forEach(it => {
            if (
              it &&
              it.entireRow !== 'row' &&
              it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              args.cell.style.color = it.textColor ? it.textColor : '#000000'
              args.cell.style.backgroundColor = it.backgroundColor
            }
          })
          res1.reverse().forEach(it => {
            if (
              it &&
              it.entireRow !== 'row' &&
              !it.dataForm.filters.rules.some(v => v.value === column)
            ) {
              args.cell.style.color = it.textColor ? it.textColor : '#000000'
              args.cell.style.backgroundColor = it.backgroundColor
            }
          })
        }
        if (args.data) {
          let keyWord =
            column !== this.comDataSource.columns[0].field
              ? 'kpiValueField'
              : 'dateField'
          let res = arr
            .filter(item => {
              if (
                item.dataForm.filters.rules.length !== 0 &&
                this.gadgetSetting[keyWord]
              ) {
                return item.dataForm.filters.rules.some(
                  v => v.key === this.gadgetSetting[keyWord]
                )
              }
            })
            .map(v => {
              v.dataForm.filters.rules = v.dataForm.filters.rules.filter(
                vi => vi.key === this.gadgetSetting[keyWord]
              )
              return v
            })
          res.reverse().forEach(it => {
            if (it) {
              let str = ''
              it.dataForm.filters.rules.forEach(ii => {
                // eslint-disable-next-line
                var val = args.data[column].toString()
                if (ii.opt === '==' || ii.opt === '!=') {
                  if (!str) {
                    str += `("${val.toString()}"  ${ii.opt
                      }   "${ii.value.toString()}")`
                  } else {
                    if (it.dataForm.filters.condition === 'and') {
                      str += `&& ("${val.toString()}"  ${ii.opt
                        }   "${ii.value.toString()}")`
                    } else {
                      str += `|| ("${val.toString()}"   ${ii.opt
                        }   "${ii.value.toString()}")`
                    }
                  }
                } else {
                  if (isNaN(val)) {
                    if (!str) {
                      str += `"${val}"${ii.opt}"${ii.value}"`
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& ("${val}"   ${ii.opt}   "${ii.value}")`
                      } else {
                        str += `|| ("${val}"   ${ii.opt}   "${ii.value}")`
                      }
                    }
                  } else {
                    if (!str) {
                      str += Number(val) + ii.opt + Number(ii.value)
                    } else {
                      if (it.dataForm.filters.condition === 'and') {
                        str += `&& (${Number(val)}   ${ii.opt}   ${Number(
                          ii.value
                        )})`
                      } else {
                        str += `|| (${Number(val)}   ${ii.opt}   ${Number(
                          ii.value
                        )})`
                      }
                    }
                  }
                }
              })
              // eslint-disable-next-line
              let res1 = eval(`${str}`)
              if (res1) {
                if (it.entireRow === 'row') {
                  args.cell.dataset.bgc = it.backgroundColor
                  args.cell.dataset.color = it.textColor
                } else {
                  args.cell.style.color = it.textColor
                    ? it.textColor
                    : '#000000'
                  args.cell.style.backgroundColor = it.backgroundColor
                }
              }
            }
          })
        }
      } catch (err) { }
    }
  },
  beforeDestroy() {
    let _this = this
    _this.$erd.uninstall(this.chartDom) 
    bus.$off('KpiSettingsRefresh')
  },
  remove () {
    this.close()
    if (this.drop.parentNode) {
      this.drop.parentNode.removeChild(this.drop)
    }
  }
}
</script>
<style scoped lang="scss">
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.bar-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }

  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
